import ast
import json
import pytz

from django.db import models, transaction
from django.utils.translation import gettext_lazy as _
from datetime import datetime

from enum import Enum



def now_Data():
    now = datetime.now()
    return now
    # from datetime import datetime
    # from pytz import timezone
    # bj_tz = timezone('Asia/Shanghai')
    # now = datetime.now(bj_tz)
    # return now

# 写一个函数用来将美国时间转化为北京时间
def convert_us_to_china_time(us_time_str, us_timezone="America/Los_Angeles"):
    """
    将美国时间转换为北京时间。
    :param us_time_str: 美国时间字符串，格式为 'YYYY-MM-DD HH:MM:SS.%f'
    :param us_timezone: 美国时区，例如 'America/New_York'
    :return: 北京时间字符串，格式为 'YYYY年MM月DD日 HH时MM分SS秒'
    """
    try:
        # 定义美国时区和北京时间
        us_tz = pytz.timezone(us_timezone)
        china_tz = pytz.timezone('Asia/Shanghai')
        
        # 解析时间字符串
        us_time = datetime.strptime(us_time_str, '%Y-%m-%d %H:%M:%S.%f')
        
        # 设定时区
        us_time = us_tz.localize(us_time)
        
        # 转换为北京时间
        china_time = us_time.astimezone(china_tz)
        
        # return china_time.strftime('%Y年%m月%d日 %H时%M分%S秒')
    except:
        # 解析ISO 8601格式的时间
        us_time = datetime.fromisoformat(us_time_str)
        
        # 设定美国时区
        us_tz = pytz.timezone(us_timezone)
        us_time = us_time.astimezone(us_tz)

        # 转换为北京时间
        china_tz = pytz.timezone('Asia/Shanghai')
        china_time = us_time.astimezone(china_tz)

    return china_time.strftime('%Y年%m月%d日 %H时%M分%S秒')

class Log(models.Model):
    class LogTypeChoices(Enum):
        SYSTEM = 'SYSTEM'  # 系统日志
        USER = 'USER'      # 用户日志
        OPERATION = 'OPERATION'  # 操作日志
        LINK = 'LINK'      # LINK日志

        @classmethod
        def choices(cls):
            # 返回元组形式的 choices
            return [(choice.value, choice.name.capitalize()) for choice in cls]
        
    class LogOptionChoices(Enum):
        CREATE = 'CREATE'  # 创建
        UPDATE = 'UPDATE'  # 更新
        DELETE = 'DELETE'  # 删除
        RUNNING = 'RUNNING'  # 执行
        LOGIN = 'LOGIN'    # 登录
        LOGOUT = 'LOGOUT'  # 登出

        @classmethod
        def choices(cls):
            return [(choice.value, choice.name.capitalize()) for choice in cls]
        
    class LogResultChoices(Enum):
        SUCCESS = '成功'
        FAIL = '失败' 
        
        @classmethod
        def choices(cls):
            return [(choice.value, choice.name.capitalize()) for choice in cls]

    LogId = models.AutoField(
        primary_key=True,
        verbose_name="日志ID",
        help_text="系统生成的日志唯一标识"
    )
    UserId = models.IntegerField(
        verbose_name="用户ID",
        help_text="执行操作的用户ID"
    )
    LogType = models.CharField(
        max_length=50,
        choices=LogTypeChoices.choices(),
        verbose_name="日志类型",
        help_text="日志记录的类别，例如系统日志或用户日志"
    )
    LogOption = models.CharField(
        max_length=50,
        choices=LogOptionChoices.choices(),
        verbose_name="日志操作",
        help_text="具体的操作类型，例如创建或删除"
    )
    LogOptionDetail = models.TextField(
        verbose_name="日志操作详情",
        help_text="关于操作的详细描述"
    )
    LogResult = models.CharField(
        max_length=100,
        verbose_name="操作结果",
        help_text="操作的结果描述，例如成功或失败"
    )
    LogStartTime = models.DateTimeField(
        verbose_name="操作开始时间",
        help_text="记录操作开始的时间"
    )
    LogEndTime = models.DateTimeField(
        verbose_name="操作结束时间",
        help_text="记录操作结束的时间"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "日志"
        verbose_name_plural = "日志管理"

    def __str__(self):
        return f"{self.UserId} - {self.LogType} - {self.LogOption}"
    
    def to_json(self):
        return {
            "LogId": self.LogId,
            "UserId": self.UserId,
            "LogType": self.LogType,
            "LogOption": self.LogOption,
            "LogOptionDetail": self.LogOptionDetail,
            "LogResult": self.LogResult,
            "LogStartTime": self.LogStartTime,
            "LogEndTime": self.LogEndTime,
            "created_at": self.created_at
        }
    
    @classmethod
    def create_Log(cls, userId, LogType, LogOption, LogOptionDetail="", LogResult=LogResultChoices.SUCCESS, LogStartTime=now_Data(), LogEndTime=now_Data()):
        try:
            log = cls(UserId=userId,LogType=LogType, LogOption=LogOption, LogOptionDetail=LogOptionDetail, LogResult=LogResult, LogStartTime=LogStartTime, LogEndTime=LogEndTime)
            log.save()
        except Exception as e:
            pass #print(e)


class LinkLog(models.Model):
    class LogResultChoices(Enum):
        SUCCESS = '成功'
        FAIL = '失败' 
        
        @classmethod
        def choices(cls):
            return [(choice.value, choice.name.capitalize()) for choice in cls]

    LogId = models.AutoField(
        primary_key=True,
        verbose_name="日志ID",
        help_text="系统生成的日志唯一标识"
    )
    LinkID = models.IntegerField(
        verbose_name="LinkID",
        help_text="Link链接对应的id",
        db_index=True
    )
    LinkInfo = models.TextField(
        default="{}", 
        verbose_name="Link信息", 
        help_text="Link链接对应的信息"
    )
    LinkURls = models.TextField(
        default="{}",
        verbose_name="Link数据集",
        help_text="Link链接对应的数据集"
    )
    ProxyInfo = models.TextField(
        default="{}",
        verbose_name="代理信息",
        help_text="Link链接对应的代理信息"
    )
    FinalUrl = models.TextField(
        default="",
        verbose_name="最终链接",
        help_text="广告的最终跳转链接"
    )
    LogOptionDetail = models.TextField(
        verbose_name="日志操作详情",
        help_text="关于操作的详细描述"
    )
    LogResult = models.CharField(
        max_length=100,
        verbose_name="操作结果",
        help_text="操作的结果描述，例如成功或失败"
    )
    LogStartTime = models.DateTimeField(
        verbose_name="操作开始时间",
        help_text="记录操作开始的时间",
        db_index=True
    )
    LogEndTime = models.DateTimeField(
        verbose_name="操作结束时间",
        help_text="记录操作结束的时间"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = "Link日志详情"
        verbose_name_plural = "Link日志管理"
        indexes = [
            models.Index(fields=["LinkID", "-LogStartTime"])
        ]

    def __str__(self):
        return f"{self.LinkID} - {self.LogStartTime}"
    
    def format_links(self, link_list):
        """将嵌套列表格式化为编号 URL 列表"""
        return [f"{i+1}、{link[0]}" for i, link in enumerate(link_list)]

    def parse_proxy_info(self, db_result):
        if isinstance(db_result, str):  
            # 如果 db_result 是字符串，先转成字典
            try:
                db_result = ast.literal_eval(db_result)
                pass #print(db_result)
                # db_result = json.loads(db_result)
            except json.JSONDecodeError:
                return {"error": "数据库返回的数据无法解析"}

        if 'IPinfo' in db_result and isinstance(db_result['IPinfo'], str):
            try:
                db_result['IPinfo'] = json.loads(db_result['IPinfo'])  # 解析 IPinfo
            except json.JSONDecodeError:
                db_result['IPinfo'] = {}  # 解析失败时返回空字典
        return db_result

    def to_json(self):
        pass #print(self.LinkURls)
        pass #print(ast.literal_eval(self.LinkURls))
        json_str = self.LinkInfo.replace("'", '"')
        LinkInfo = json.loads(json_str)
        pass #print("1111111")
        pass #print(self.ProxyInfo)
        pass #print("1111111")
        try:
            ip = self.parse_proxy_info(self.ProxyInfo).get("IPinfo").get("ip")
        except Exception as e:
            ip = f"{e}"
        return {
            "LogId": self.LogId,
            "LinkID": self.LinkID,
            # "LogOptionDetail": self.LogOptionDetail,
            "OfferLink": LinkInfo.get("OfferLink"),
            "TargetNation": LinkInfo.get("TargetNation"),
            "redirect": LinkInfo.get("redirect"),
            "URLldentifiers": LinkInfo.get("URLldentifiers"),
            "LinkInfo": json.dumps(self.LinkInfo),
            "LinkURls": self.format_links(ast.literal_eval(self.LinkURls)),
            "ProxyInfo": self.parse_proxy_info(self.ProxyInfo),
            "FinalUrl": self.FinalUrl,
            "LogResult": self.LogResult,
            "Ip": ip,
            "LogStartTime": convert_us_to_china_time(self.LogStartTime.isoformat()) if self.LogStartTime else None,
            "LogEndTime": convert_us_to_china_time(self.LogEndTime.isoformat()) if self.LogEndTime else None,
            "created_at": convert_us_to_china_time(self.created_at.isoformat()) if self.created_at else None
        }
    
    def save(self, *args, **kwargs):
        with transaction.atomic():
            # 保存新数据
            super().save(*args, **kwargs)

            # 根据条件获取记录ID（时间倒序）
            datas = LinkLog.objects.filter(
                LinkID=self.LinkID
            ).order_by("-LogStartTime", "-LogId").values_list("LogId", flat=True)

            # 计算删除的数量
            if (datass := datas.count() - 50) > 0:
                # 直接sql删除
                LinkLog.objects.filter(
                    LogId__in=list(datas[50:50+datass])
                ).delete()




    # @classmethod
    # def create_Log(cls, LinkID, LogOptionDetail="", LogResult=LogResultChoices.SUCCESS, LogStartTime=now_Data(), LogEndTime=now_Data()):
        
    #     try:
    #         cls.save({
    #             LinkID="LinkID",
    #         })
    #     except Exception as e:
    #         pass #print(e)


    # # tasks.py（Celery异步任务）
    # from celery import shared_task
    # @shared_task
    # def trim_records(keyword):
    #     records = KeywordData.objects.filter(keyword=keyword)
    #     if (excess := records.count() - 50) > 0:
    #         KeywordData.objects.filter(
    #             id__in=records.order_by('created_at')[:excess].values_list('id', flat=True)
    #         ).delete()

    # # models.py修改保存逻辑
    # def save(self, *args, **kwargs):
    #     super().save(*args, **kwargs)
    #     trim_records.delay(self.keyword)  # 异步触发
